package db

import (
	"fmt"
	"github.com/google/uuid"
	"github.com/jinzhu/gorm"
	"sola/common"
	"time"
)

type Classify struct {
	common.BaseModel
	ClassifyId         string `json:"classify_id" uri:"classify_id" gorm:"size:36;NOT NULL"`
	ClassifyName       string `json:"classify_name" gorm:"size:64;NOT NULL"`
	AuthorId           string `json:"author_id" gorm:"size:36"`
	AuthorName         string `json:"author_name" gorm:"size:64"`
	AuthorNickName     string `json:"author_nick_name" gorm:"size:64"`
	UpdateUserId       string `json:"update_user_id" gorm:"size:36"`
	UpdateUserName     string `json:"update_user_name" gorm:"size:64"`
	UpdateUserNickName string `json:"update_user_nick_name" gorm:"size:64"`
	SvgName            string `json:"svg_name" gorm:"size:64"`
	Status             string `json:"status"`
	Changeable         bool   `json:"changeable"`
}

func (classify *Classify) BeforeCreate(scope *gorm.Scope) error {
	return scope.SetColumn("classify_id", uuid.New().String())
}

func (classify *Classify) BeforeSave(scope *gorm.Scope) error {
	return scope.SetColumn("updated_at", time.Now())
}

func CountClassify(baseSearchModel *common.BaseSearchModel) (count int) {
	searchDB := db.Table("classifies").Where("classify_name like ? and status like ? and deleted_at is  NULL", "%"+baseSearchModel.Name+"%", "%"+baseSearchModel.Status+"%")
	if baseSearchModel.UserId != "" {
		searchDB = searchDB.Where("author_id = ?", baseSearchModel.UserId)
	}
	searchDB.Count(&count)
	return
}

func GetClassifyList(searchModel *common.BaseSearchModel) (classifies []*Classify) {
	searchDB := db.Table("classifies").Where("classify_name like ? and status like ?",
		"%"+searchModel.Name+"%", "%"+searchModel.Status+"%")
	if searchModel.UserId != "" {
		searchDB = searchDB.Where("author_id = ?", searchModel.UserId)
	}
	if searchModel.Limit > 0 {
		searchDB = searchDB.Offset((searchModel.Page - 1) * searchModel.Limit).Limit(searchModel.Limit)
	}
	if searchModel.Sort != "" {
		searchDB = searchDB.Order(searchModel.Sort)
	}
	searchDB.Find(&classifies)
	return classifies
}

func FindByClassifyId(classify_id string) (classify *Classify, err error) {
	var classify_db Classify
	classify_db.ClassifyId = classify_id
	db.Where("classify_id = ?", classify_id).First(&classify_db)
	if classify_db.Id <= 0 {
		err = fmt.Errorf("classify:%s is not found", classify_id)
		return
	}
	classify = &classify_db
	return
}
